package edu.uob;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Comparator;
import java.util.stream.Stream;

public class DatabaseManager {
    public static String dropDB(String name) {
        String pathStr = "." + File.separator + "databases" + File.separator + name;

        Path path = Paths.get(pathStr);
        try {
            if (Files.exists(path) && Files.isDirectory(path)) {
                try (Stream<Path> stream = Files.walk(path)) {
                    stream.sorted(Comparator.reverseOrder())
                            .map(Path::toFile)
                            .forEach(file -> {
                                if (!file.delete()) {
                                    System.err.println("[ERROR]: Failed to delete: " + file);
                                }
                            });
                }
                if (!Files.exists(path)) {
                    return "[OK]";
                } else {
                    return "[ERROR]: Unable to drop database '" + name + "'.";
                }
            } else {
                return "[ERROR]: Database '" + name + "' does not exist.";
            }
        } catch (IOException e) {
            return "[ERROR]: An error occurred while dropping database '" + name + "'.";
        }
    }
}
